﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetCoreConfigIntroduce.Options;

namespace NetCoreConfigIntroduce
{
    public class Startup
    {
        public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
        {
            Configuration = configuration;
            //1. 获取文本值
            var data1 = configuration["data1"];
            var IncludeScopes = configuration.GetValue<bool>("Logging:IncludeScopes");
            var Default = configuration.GetValue<string>("Logging:LogLevel:Default");

            //2.获取配置源
            var logging = configuration.GetSection("Logging");
            loggerFactory.AddConsole(logging);
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //3. 手动配置自定义对象值
            var ComplexOptionsSection = Configuration.GetSection("ComplexOptions");
            var complexOptions = new ComplexOptions(ComplexOptionsSection);

            //4. 自动配置自定义对象
            services.AddOptions();
            services.Configure<AutoConfig>(Configuration.GetSection("AutoConfig"));

            //5.绑定复杂数据类型
            services.Configure<Profile>(Configuration.GetSection("Profile"));

            //6.绑定集合对象
            services.Configure<Collection<Profile>>(Configuration.GetSection("Profiles"));

            //7. 绑定字典
            services.Configure<Dictionary<string, Profile>>(Configuration.GetSection("DictionaryProfiles"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
